﻿using System;
using System.Text.Json;
using System.Text.Json.Serialization;
using zijian666.SuperConvert.Core;
using zijian666.SuperConvert.Extensions;

namespace zijian666.SuperConvert.Json
{

    internal class JsonValueConverter<T> : JsonConverter<T>
    {
        public override bool CanConvert(Type type)
            => type == typeof(T);

        public override T Read(ref Utf8JsonReader reader, Type type, JsonSerializerOptions options)
        {
            var value = JsonSerializer.Deserialize<string>(ref reader, options);
            return (T)ConvertContext.Current.Convert(type, value).Value;
        }

        public override void Write(Utf8JsonWriter writer, T value, JsonSerializerOptions options)
        {
            var result = ConvertContext.Current.Convert<string>(value);
            if (result.Success)
            {
                JsonSerializer.Serialize(writer, result.Value, options);
            }
            else
            {
                JsonSerializer.Serialize(writer, value, options);
            }
        }
    }
}
